<?php


use app\BaseController;

class  Wx extends BaseController
{
    /**
     * 微信授权入口
     */
    public function jsSign()
    {
        $result = [
            "status" => "no",
            "msg" => "执行失败",
            "data" => [],
            "req" => \request()->all()
        ];

        $reqUrl = $this->request->get('url', '');
        if ($reqUrl) {
            $wxApi = \WeChatApi::getInstance();
            $result["data"] = $wxApi->getJsSign($reqUrl);
            if ($result["data"]) {
                $result["status"] = "ok";
                $result["msg"] = "执行成功";
                $result['req'] = $this->request->param();
            }
        } else {
            $result["msg"] = "url参数缺少";
        }

        return json($result);
    }

    /**
     * 授权回调处理
     */
    public function oauth()
    {
        //保存刷新的用户信息
        $req = request();
        $uid = isset($req["uid"])
            ? $req["uid"]
            : 0;//用户信息

        $from = isset($req["from"])
            ? $req["from"]
            : 0;
        $state = $uid . "from" . $from;
        $wxApi = \WeChatApi::getInstance();
        $url = $this->request->host() . "/index.php/common/wx/oauthCb";
        $redirectUrl = $wxApi->getOauthRedirect($url, $state);
        $result = [
            "status" => "ok",
            "msg" => "ok",
            "data" => ["url" => $redirectUrl],
            "req" => \request()->all()
        ];
        return json($result);
    }

    /**
     * 授权后回调获取用户信息
     */
    public function oauthCb()
    {
        $wxApi = \WeChatApi::getInstance();
        //获取用户信息
        $token = $wxApi->getOauthAccessToken();
        //获取用户信息
        $wxUser = $wxApi->getOauthUserinfo($token["access_token"], $token["openid"]);
        $state = $_GET["state"];

        if ($wxUser && $state) {
            $userAndFrom = explode("from", $state);
            $uid = isset($userAndFrom[0]) ? $userAndFrom[0] : 0;
            $from = isset($userAndFrom[1]) ? $userAndFrom[1] : "";
            switch ($from) {
                case "webLogin":
                    //uid 患者id, wxUser微信信息
                    $this->loginHandle($uid, $wxUser);
            }
        }
    }

    private function loginHandle($uid, $wxUser)
    {

    }

}
